package org.permission.utils;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.permission.pojo.SysPermission;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class PermissionInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//先判断用户是否访问的是匿名资源
		Set<String> keys = ResourceUtils.getPropertyKeys("annonymousURLS.properties");
		String url = request.getRequestURI();
		for (String string : keys) {
			if(url.contains(string)) {
				return true;
			}
		}
		
		//先判断用户是否访问的是公共资源
		Set<String> commonUrls = ResourceUtils.getPropertyKeys("commonURLs.properties");
		for (String string : commonUrls) {
			if(url.contains(string)) {
				return true;
			}
		}
		
		List<SysPermission> permissionList = (List<SysPermission>) request.getSession().getAttribute(Constant.PERMISSION_LIST);
		for (SysPermission per : permissionList) {
			System.out.println("url :  " + per.getUrl());
			if(per.getUrl() != null && !per.getUrl().equals("")) {
				if(url.contains(per.getUrl())) {
					return true;
				}
			}
		}
		request.getRequestDispatcher("/refuse").forward(request, response);
		return false;
	}
}
